/**
 * 复写$.get $.post 方法 在内部自动添加basePath
 * 杨雄
 */
jQuery.each(["get", "post"], function (i, method) {
    jQuery[method] = function (url, data, callback, type) {
        if (jQuery.isFunction(data)) {
            type = type || callback;
            callback = data;
            data = undefined;
        }
        if (!url.startsWith(basePath)) {
            url = basePath + url;
        }
        return jQuery.ajax({
            type: method,
            url: url,
            data: data,
            success: callback,
            dataType: type
        });
    };
});
var FormType = {undefined: undefined, add: "add", edit: "edit", info: "info"};
var formType = FormType.undefined;
// layer.closeAll(); //疯狂模式，关闭所有层
// layer.closeAll('dialog'); //关闭信息框
// layer.closeAll('page'); //关闭所有页面层
// layer.closeAll('iframe'); //关闭所有的iframe层
// layer.closeAll('loading'); //关闭加载层
// layer.closeAll('tips'); //关闭所有的tips层
// layer.close(index);
function layerOpen(title, url) {
    var content = "";
    $.ajaxSettings.async = false;
    $.ajax({
        type: "get",
        url: basePath + url,
        async: false,
        success: function (data) {
            content = data;
        }
    });
    var index = layer.open({
        type: 1,
        // title: title,
        title: " ",
        // title: false, //不显示标题
        area: ['70%', '80%'],
        // closeBtn: 0,//不显示关闭按了
        content: content
    });
    return index;
}

/**
 * yangxiong
 * @param url
 */
var formPanels = [];

var isLoadPanel;

function showFormPanel(url, title, closeBut, bomb_type,callback) {
    var param;
    if (arguments.length === 1) {//为了兼容以前的写法,没办法,只能用这种方法重构了
        param = url;
        url = param.url;
        title = param.title;
        closeBut = param.closeBtn;
        bomb_type = param.type;
    }
    if (isLoadPanel)
        return;
    isLoadPanel = true;
    const id = url.replace(/\//g, "").replace('.', '');
    $('body').find("#" + id + "_bg").remove();//避免重复加载
    let formPanel;
    const panelOpt = {
        // width: width,//高
        // height: height,//宽
        bombType: bomb_type ? bomb_type : BOMB_TYPE2,
        valForm: {},//验证
        action: "",//表单提交地址
        event: {
            onClosed: function (obj) {
                $('body').find("#" + id + "_bg").remove();
                formPanels.splice($.inArray(formPanel, formPanels), 1)
            },
            okBtnClick: function (eventObj, panel, type) {
                type.success = 2;
                // formPanel.close();
            },
            submitSuccessed: function (data, panelObj) {
            }
        }
    };
    const div = $('<div ></div>');
    div.load(basePath + url, function () {
        const pannel = $('<div class="pannel_bg" id="' + id + '_bg"' + '>' +
            '    <div class="panel" id="' + id + '">' +
            '       <div class=\'titleBar\' ><div class="title"></div><div class="closeBtn">返回</div></div>' +
            '       ' + div.html() +
            '   </div>' +
            '</div>');
        pannel.appendTo('body');
        formPanel = $("#" + id).wdfPanel("FormPanel", panelOpt);
        formPanel.show(title);
        slideUpInput(formPanel.find(".slideUpBtn"));
        if (closeBut) {
            $('body').find("#" + id + " .closeBtn").show();
        }
        formPanels.push(formPanel);
        isLoadPanel = false;
        if (param && $.isFunction(param.load)) {
            param.load(formPanel);
        }
    });

}

function closePanel(obj) {
    $(obj).parents(".pannel_bg").find(".closeBtn").click()
}

function layerMsg(obj, call) {
    if (obj.msg) {
        layer.msg(obj.msg, {
            time: 1000
        }, function () {
            if (obj.status === 1) {
                layer.closeAll();//关闭所有弹框
                closeFormPanel();//关闭所有弹框
                if (call !== undefined)
                    call();
            }
        })
    } else {
        layer.msg(obj, {
            time: 1000
        }, function () {
            layer.closeAll();//关闭所有弹框
            closeFormPanel();//关闭所有弹框
            if (call !== undefined)
                call();
        })
    }
}

function closeFormPanel() {
    for (var i = formPanels.length; i--; i > 0) {
        try {
            formPanels[i].close()
        } catch (e) {
        }
    }
}

function layerConfirm(msg, call, close) {
    layer.confirm(msg, {
        btn: ['确定', '取消'] //按钮
    }, function (index) {
        if (call)
            call();
        layer.close(index);
    }, function (index) {
        if (close)
            close();
        layer.close(index);
    });
}

function layerCloseAll() {
    layer.closeAll();
}

// 表单验证
function validateForm(formId, call) {
    $(formId).validate({
        errorClass: "validate_error",
        errorPlacement: function (error, element) {
            error.appendTo(element.parent().next("td"));
            error.appendTo(element.parent().next("div"));
        },
        submitHandler: function () {
            call();
        },

    });
    validateDefaultRules(formId);
}

function validateForm2(formId) {
    var validateParam = [];
    $(formId).find("input").each(function () {
        var type = $(this).attr("required");
        if (type !== undefined) {
            var id = $(this).attr("id");
            var placeholder = $(this).attr("placeholder");
            validateParam.push({
                inputname: id,
                isnull: true,
                isnullmsg: placeholder,
                msgType: "EditGridRowMsg",
                autoremove: 1666
            })
        }
        textTrimByElem(this)
    });
    return executeVal(validateParam);
}


//validate 规则
function validateDefaultRules(formId) {
    jQuery.validator.addMethod("numberDecimal", function (value, element) {
        var returnVal = true;
        var ArrMen = value.split(".");    //截取字符串
        if (ArrMen.length == 2) {
            if (ArrMen[1].length > 2) {    //判断小数点后面的字符串长度
                returnVal = false;
                return false;
            }
        }
        return returnVal;
    }, "小数点后最多为两位");

    $(formId).find("input").each(function () {
        var type = $(this).attr("type");
        switch (type) {
            case "text":
                if ($(this).attr("maxlength")) {
                    $(this).rules("add", {maxlength: 50});
                    $(this).attr("maxlength", 51);
                }
                break;
            case "numberDecimal":
                $(this).rules("add", {number: true});
                $(this).rules("add", {numberDecimal: true});
                break;
            case "number":
                $(this).rules("add", {number: true,});
                break;
            case "digits":
                $(this).rules("add", {digits: true,});
                break;
            case "email":
                $(this).rules("add", {email: true});
                break;
        }
        textTrimByElem(this)
    });
    $(formId).find("textarea").each(function () {
        if ($(this).attr("maxlength")) {
            $(this).rules("add", {maxlength: 256});
            $(this).attr("maxlength", 257);
        }
        textTrimByElem(this)
    });
    //
    // $(formId).find("select").each(function () {
    //     if ($(this).attr("required") !== undefined) {
    //         $(this).after('<lable class="required_lable">*</lable>')
    //     }
    // });
}

//去除前后空格
function textTrimByElem(obj) {
    $(obj).blur(function () {
        var trim_val = $(obj).val().trim();
        $(obj).val(trim_val);
    })
}

function formatPicDownloadBtn(columnValue, dDir) {
    var downLoadDocFilesBtn;
    if (columnValue && columnValue != "") {
        downLoadDocFilesBtn = $("<a  class='enclosure_btn' id='enclosureBtn_ProgressLogsList_DppDetailTab1_" + i + "' " +
            " href=\"javascript:\"" +
            " >查看</a>");
        downLoadDocFilesBtn.data("docFiliesUrl", columnValue);
        downLoadDocFilesBtn.bind("click", function (e) {
            stopPropagation(e);
            littileTools.filesListPanel.show($(this).data("docFiliesUrl"), $(this), dDir);
        });

    } else {
        // downLoadDocFilesBtn = $("<a  class='have_no_file' id='enclosureBtn_ProgressLogsList_DppDetailTab1_" + i + "' " +
        //     " href=\"javascript:\"" +
        //     " >无附件</a>");
        downLoadDocFilesBtn = "";
    }
    return [downLoadDocFilesBtn];
}

//表单验证----------------------------end-------------------


function getNotNullOpt(msg) {
    if (msg === undefined) {
        msg = "不能为空";
    }
    return {
        isnull: true,
        isnullmsg: msg,
        rightmove: -70,
        autoremove: valMsgRemoveTime
    }
}

function validateElemNull(id, msg) {
    if (msg === undefined) {
        msg = "不能为空";
    }
    return !executeVal([{
        inputname: id,
        isnull: true,
        isnullmsg: msg,
        msgType: "EditGridRowMsg",
        autoremove: 1666
    }])
}

//表单序例化成对象操作
$.fn.serializeObject = function () {
    var o = {};
    var a = this.serializeArray();
    $.each(a, function () {
        if (o[this.name]) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');

        } else {
            o[this.name] = this.value || '';
        }

    });
    return o;
};